<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/21 0021
 * Time: 22:09
 */

namespace Lib\Core\WebSocket;


use Lib\Core\Config;
use Lib\Core\Http;
use Swoole\WebSocket\Server;

class WebSocket extends Http
{
    public function run()
    {
        //热重启
        //支持http请求 解析路由
        //能拥有webSocket控制器
        $config = Config::getInstance();
        $config->load();//载入配置文件

        $wsSet = $config->get('ws');
        $this->server = new Server($wsSet['host'], $wsSet['port']);
        $this->server->set($wsSet['swoole_setting']);
        $this->server->on('Start', [$this, 'start']);
        $this->server->on('workerStart', [$this, 'workerStart']);
        $this->server->on('open', [$this, 'open']);
        $this->server->on('message', [$this, 'message']);
        $this->server->on('close', [$this, 'close']);

        //tcp服务端口监听
        if ((int)$wsSet['tcpable'] === 1) {
            $tcp = $config->get('tcp');
            $this->registerTcp($tcp);
        }
        if ($wsSet['enable_http']) {
            $this->server->on('request', [$this, 'request']);
        }

        $this->server->start();
    }

    public function open($server, $request)
    {
        $fd = $request->fd;
        $path = $request->server['path_info'];
        WebSocketContext::init($fd, $path);
        Dispatch::open($server, $request, $path);
    }

    public function message($server, $frame)
    {
        $fd = $frame->fd;
        $path = WebSocketContext::get($fd);
        Dispatch::message($server, $frame,$path);
    }

    public function close($server, $fd)
    {
        $path = WebSocketContext::get($fd);
        Dispatch::close($server, $fd,$path);
        WebSocketContext::del($fd);
    }

    public function request($request, $response)
    {
        $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
    }
}